#!/usr/action/env python
# -*- coding: utf-8 -*-
# title       : clean maya unknownPlugin and unknown node
# description :
# author      : Jarry
# mtine       :
# version     :
# usage       :
# notes       :

# Built-in modules
import os, sys
import re
# Third-party modules
# add license check
# import THLicense.CheckLicense as cl
#
# cl.CheckLicense()

try:
    import maya.cmds as cmds
    import pymel.core as pm
    import maya.mel as mel
except:
    pass
from .MayaScannerCleanerJarryFix import *
import logging
logging.basicConfig()
log = logging.getLogger("MayaCleanOptimize")
log.setLevel(logging.DEBUG)


class MayaCleanOptimize:
    def __init__(self):
        pass

    def unknown_plugin(self):
        unknown_plugins = cmds.unknownPlugin(q=True, list=True) or []
        for up in unknown_plugins:
            try:
                cmds.unknownPlugin(up, remove=True)
            except:
                pass
        self.d3d()
        self.look()
        self.script_clean()

    def unknown_node(self):
        for node in cmds.ls(type='unknown'):
            try:
                cmds.lockNode(node, l=False)
                cmds.delete(node)
            except:
                pass

    def scanner_clean(self):
        try:
            jarry_currentfix_save(save=False)
        except:
            pass

    def script_clean(self):
        try:
            maya_path = cmds.internalVar(userAppDir=True) + '/scripts'
            scirpt_file_list = os.listdir(maya_path)
            if 'vaccine.py' in scirpt_file_list:
                for f in [u'userSetup.py', u'vaccine.py', u'vaccine.pyc']:
                    to_del_file = maya_path + '/' + f
                    if os.path.exists(to_del_file):
                        os.remove(to_del_file)
            script_list = ['breed_gene', 'vaccine_gene', 'pasted__MayaMelUIConfigurationFile1',
                           'pasted__MayaMelUIConfigurationFile']
            for sc in script_list:
                if cmds.objExists(sc):
                    cmds.delete(sc)
        except:
            pass

    def d3d(self):
        # 清除 onModelChange3dc 错误
        # Get all model editors in Maya and reset the editorChanged event
        # 获取Maya中的所有模型编辑器并重置 editorChanged 事件
        try:
            for item in pm.lsUI(editors=True):
                if isinstance(item, pm.ui.ModelEditor):
                    pm.modelEditor(item, edit=True, editorChanged="")
        except:
            pass

    def look(self):
        mel.eval('outlinerEditor -edit -selectCommand "" "outlinerPanel1";')

    def deleteNode(self, nodeName):
        if cmds.objExists(nodeName):
            try:
                cmds.delete(nodeName)
            except:
                log.error("can not delete node %r" % nodeName, exc_info=1)

    def clean_mr_nodes(self):
        mrnodes = [u'miDefaultFramebuffer', u'mentalrayGlobals',
                   u'mentalrayItemsList', u'Draft', u'DraftMotionBlur',
                   u'DraftRapidMotion', u'miContourPreset', u'miDefaultOptions',
                   u'Preview', u'PreviewCaustics', u'PreviewFinalGather',
                   u'PreviewGlobalIllum', u'PreviewImrRayTracyOff',
                   u'PreviewImrRayTracyOn', u'PreviewMotionblur',
                   u'PreviewRapidMotion', u'Production', u'ProductionFineTrace',
                   u'ProductionMotionblur', u'ProductionRapidFur',
                   u'ProductionRapidHair', u'ProductionRapidMotion']  #

        for node in mrnodes:
            self.deleteNode(node)

        log.info('clean_mr_nodes > delete all mentalRay nodes in scene!  ok....')

    def delete_invalid_nurbs_surface(self):
        num = mel.eval("deleteUnusedNurbsSurfaces")
        num += mel.eval(
            "deleteUnusedCommon_Multi({\"stitchSrf\",\"rebuildSurface\",\"insertKnotSurface\",\"avgNurbsSurfacePoints\"},0,(uiRes(\"m_cleanUpScene.kDeletingUnusedPointConstraints\")))")
        log.info("Delete invalid nurbs curves and surfaces > %s" % num)

    def delete_unused_nurbscurve(self):
        num = mel.eval(
            "deleteUnusedInUnusedHierarchy( \"nurbsCurve\", 0, (uiRes(\"m_cleanUpScene.kDeletingUnusedNurbsCurves2\")) )")
        log.info("Delete unused nurbs curves > %s" % num)

    def delete_unused_locators(self):
        num = mel.eval("deleteUnusedLocators()")
        log.info("Delete unused locators > %s" % num)

    def delete_unused_const(self):
        num = mel.eval("deleteUnusedConstraints()")
        log.info("Delete unused constraints > %s" % num)

    def delete_unused_pairblends(self):
        num = mel.eval("deleteUnusedPairBlends()")
        log.info("Delete unused pairBlends > %s" % num)

    def delete_unused_deformers(self):
        num = mel.eval("deleteUnusedDeformers()")
        log.info("Delete unused deformers > %s" % num)

    def delete_unused_skincluster(self):
        num = mel.eval("removeAllUnusedSkinInfs()")
        log.info("Delete unused skin influences > %s" % num)

    def delete_unused_expressions(self):
        num = mel.eval("deleteUnusedExpressions()")
        log.info("Delete unused expressions > %s" % num)

    def delete_unused_groupId(self):
        num = mel.eval(
            "deleteUnusedCommon( \"groupId\", 0, (uiRes(\"m_cleanUpScene.kDeletingUnusedGroupIDNodes2\")) ) ")
        log.info("Delete unused groupId nodes > %s" % num)

    def delete_unused_snapshots(self):
        num = mel.eval(
            "deleteUnusedCommon( \"snapshot\", 0, (uiRes(\"m_cleanUpScene.kDeletingUnusedSnapshotNodes2\")) ) ")
        log.info("Delete unused snapshot nodes > %s" % num)

    def delete_unused_unitConversion(self):
        num = mel.eval(
            "deleteUnusedCommon_Multi( {\"unitConversion\",\"timeToUnitConversion\",\"unitToTimeConversion\"}, 1, (uiRes(\"m_cleanUpScene.kDeletingUnusedUnitConversionNodes2\"))  );")
        log.info("Delete unused unitConversion nodes > %s" % num)

    def delete_unused_rendering(self):
        num = mel.eval("MLdeleteUnused()")
        log.info("Delete unused rendering nodes > %s" % num)

    def delete_empty_transforms(self):
        num = mel.eval("deleteEmptyGroups()")
        log.info("Delete empty transforms > %s" % num)

    def delete_display_layers(self):
        num = mel.eval("deleteEmptyLayers(\"Display\")")
        log.info("Delete empty display layers > %s" % num)

    def delete_render_layers(self):

        num = mel.eval("deleteEmptyLayers(\"Render\")")
        log.info("Delete empty Render layers > %s" % num)

    def delete_unused_sets(self):
        num = mel.eval("deleteUnusedSets()")
        log.info("Delete unused sets > %s" % num)

    def delete_unused_partitions(self):
        num = mel.eval(
            "deleteUnusedCommon(\"partition\",0, (uiRes(\"m_cleanUpScene.kDeletingEmptyPartitions2\")) )")
        log.info("Delete unused partitions > %s" % num)

    def delete_unused_reference_nodes(self):
        num = mel.eval("RNdeleteUnused")
        log.info("Delete unused reference nodes > %s" % num)

    def delete_unused_brushes(self):
        num = mel.eval("deleteUnusedBrushes")
        log.info("Delete unused brushes > %s" % num)

    def delete_unknown_nodes(self):
        num = mel.eval("deleteUnknownNodes")
        log.info("Delete unknown nodes > %s" % num)

    def delete_dup_shading_network(self):
        num = mel.eval("removeDuplicateShadingNetworks(0)")
        log.info("Delete duplicate shading networks > %s" % num)

    def delete_unused_animcurves(self):
        num = mel.eval(
            "deleteUnusedCommon(\"animCurve\", 0, (uiRes(\"m_cleanUpScene.kDeletingUnusedAnimationCurves\"))  ) ")
        log.info("Delete Unused Animations Curves > %s" % num)

    def delete_unused_clips(self):
        num = mel.eval("deleteUnusedTrax(\"clips\")")
        log.info("Delete Unused clips > %s" % num)

    def delete_unused_poses(self):
        num = mel.eval("deleteUnusedTrax(\"poses\")")
        log.info("Delete Unused poses > %s" % num)

    def delete_unused_nurbsSurface(self):
        num = mel.eval("deleteUnusedNurbsSurfaces")
        log.info("Delete Unused nurbsSurfaces > %s" % num)

    def delete_pasted_name(self):
        pastednodes = [k for k in cmds.ls() if "pasted__" in k]
        for node in pastednodes:
            try:
                cmds.rename(node, node.replace("pasted__", ""))
            except:
                pass

    def rest_default_setting(self):
        # 解锁创建模型及贴图创建无法在视图和Node面板中显示问题
        cmds.lockNode('initialShadingGroup', l=0, lockUnpublished=0)
        cmds.lockNode('defaultTextureList1', l=0, lockUnpublished=0)
        cmds.lockNode('initialParticleSE', l=0, lockUnpublished=0)


    def cleanup_uiconfig(self):
        if cmds.objExists("uiConfigurationScriptNode"):
            bs = cmds.scriptNode('uiConfigurationScriptNode', q=True, bs=True)
            if bs:
                bs = re.sub(r'DCF_updateViewportList;', bs, '')
            cmds.scriptNode('uiConfigurationScriptNode', e=True, bs=bs)



if __name__ == "__main__":
    ins = MayaCleanOptimize()
    ins.unknown_plugin()
    ins.unknown_node()
